using System.Reflection;
using System.Text.RegularExpressions;
using ViScript.Core.ParameterRules;
using ViScript.Core.Utils;

namespace ViScript.Core
{
    public interface ISentenceRuleFactory
    {
        SentenceRule CreateSentenceRule(object obj, MethodInfo method);
    }

    public class SentenceRuleFactory : ISentenceRuleFactory
    {
        private readonly ITextFactory textFactory;
        private readonly IParameterRule parameterRule;

        public SentenceRuleFactory(ITextFactory textFactory, IParameterRule parameterRule)
        {
            this.textFactory = textFactory;
            this.parameterRule = parameterRule;
        }

        public static Regex GenerateSentenceRegex(MethodInfo method)
        {
            string pattern = method.Name;
            pattern = pattern.Replace("_", @"\s+");
            foreach (ParameterInfo parameter in method.GetParameters())
            {
                pattern = pattern.Replace(parameter.Name, string.Format("(?<{0}>.+)", parameter.Name));
            }
            return new Regex(pattern, RegexOptions.IgnoreCase);
        }

        public SentenceRule CreateSentenceRule(object obj, MethodInfo method)
        {
            return new SentenceRule(obj, method, GenerateSentenceRegex(method), textFactory, parameterRule);
        }
    }
}